#!/bin/sh

#  Copyright 2018 RealVNC Ltd.
#
#  Script to build and install the VNC virtual framebuffer driver for Xorg
#

if [ ! $(id -u) = 0 ]; then
    echo "This must be run as root, please run via sudo or su"
    exit 1
fi

confirm()
{
  while true; do
    read -r -p "$1" RESPONSE
    case "$RESPONSE" in
      [yY]) return 0 ;;
      [nN]) return 1 ;;
      *) echo "Please enter y or n"
    esac
  done
}

echo
echo "This script will attempt to build and install the VNC virtual framebuffer driver for the Xorg server on your system."
confirm "Do you wish to continue? [y/n]:" || exit 0
echo

# Start redirecting stdout and stderr to the log file
LOG=buildAndInstall.log
rm -f $LOG
exec 3>&1 
exec 1>$LOG 2>&1

info()
{
    echo "* $1" >&3
    echo
    echo "* $1"
    echo
}

error()
{
    echo >&3
    echo "! ERROR: $1" >&3
    echo "! Please see file '${LOG}' for details" >&3
    echo >&3
    echo
    echo "! ERROR: $1"
    echo
    exit 1
}

run()
{
    echo "> $@"
    $@
}

info "Checking system"

ARCH=`uname -m`
if [ "${ARCH}" = "x86_64" -a -d /usr/lib64 ]; then
    LIBDIR="lib64"
else
    LIBDIR="lib"
fi

echo "Arch: ${ARCH}"
DRV_INSTALL_PATH="/usr/${LIBDIR}/xorg/modules/drivers/"
if [ ! -d "${DRV_INSTALL_PATH}" ]; then
    error "Xorg driver path '${DRV_INSTALL_PATH}' does not exist"
fi
echo "Xorg driver path: ${DRV_INSTALL_PATH}"

info "Ensuring build dependencies are met"

if command -v yum >/dev/null 2>&1; then
    BUILD_DEPS="autoconf automake libtool pkgconfig xorg-x11-server-devel xorg-x11-proto-devel"
    run yum -y install ${BUILD_DEPS}

elif command -v apt-get >/dev/null 2>&1; then
    BUILD_DEPS="autoconf automake libtool pkg-config xserver-xorg-dev xutils-dev x11proto-randr-dev x11proto-render-dev"
    run apt-get -y install ${BUILD_DEPS}
fi

info "Configuring build"

ARTIFACTS="aclocal.m4 autom4te.cache compile config.h.in config.sub depcomp ltmain.sh bld config.guess configure install-sh Makefile.in missing"
run rm -rf ${ARTIFACTS}
run mkdir bld
cd bld
run ../autogen.sh --disable-static || error "Failed to configure build"

info "Building driver"

DRV_PATH="src/.libs/"
DRV_NAME="vnc_drv.so"
DRV="${DRV_PATH}${DRV_NAME}"
run make || error "Failed to build driver"

info "Installing driver"

run install -vbs "${DRV}" "${DRV_INSTALL_PATH}"
if [ ! -f "${DRV_INSTALL_PATH}${DRV_NAME}" ]; then
    error "Failed to install driver"
fi

info "Cleaning up"
cd ..
run rm -rf ${ARTIFACTS}

info "Success"
exit 0
